import mpx from '@mpxjs/core'
import mpxFetch from '@mpxjs/fetch'
import { wxGetStorageSync } from './WxApiUtils'
import Tips from './Tips'
import store from '../store/index'
import { ACCESS_TOKEN } from '../store/mutation-types'

const unAuthUrl = ['login', 'index/', 'product/']

mpx.use(mpxFetch)

// console.log('[process.env.BASE_API]',process.env.BASE_API);
const service = mpx.xfetch

service.interceptors.request.use(
  async (config) => {
    // console.log('[config]', config)
    // 让每个请求携带token
    config.header = {}
    if (store.getters.token) {
      config.header['Authorization'] = wxGetStorageSync(ACCESS_TOKEN) // 设置token
    } else if (!unAuthUrl.some((path) => config.url.indexOf(path) > -1)) {
      await store.dispatch('refreshLogin')
      config.header['Authorization'] = wxGetStorageSync(ACCESS_TOKEN) // 设置token
    }
    config.url = process.env.BASE_API + config.url // 加载基础路径
    if (!config.method) config.method = 'POST' // 默认请求方式为POST 方式
    // 也可以返回promise
    return config
  },
  (error) => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// respone interceptor
service.interceptors.response.use(
  async (response) => {
    // console.log('[response]', response)
    const wxCode = response.statusCode
    // 微信请求错误
    if (wxCode !== 200) {
      if (wxCode === 401) {
        await store.dispatch('refreshLogin')
        // Tips.toast(resp.msg)
        // store.dispatch('LogOut')
        // wx.redirectTo({
        //   url: '/pages/login',
        // })
        // return true
      } else {
        return Promise.reject(new Error(response.data))
      }
    } else {
      const resp = response.data
      // console.log('[resp]', resp)
      // 判断返回结果
      if (resp.code === -1) {
        await store.dispatch('refreshLogin')
        Tips.toast('登录已过期，请重试')
        // return true
      } else if (resp.code === 1) {
        // console.log('[接口失败]', resp.msg)
        Tips.error(resp.msg, 1200)
        // return Promise.reject(resp.msg)
      }
      return resp
    }
  },
  (error) => {
    console.log('[response error]', error)
    return Promise.reject(error)
  }
)

export default service
